<% pattern_x   = defined?(pattern) && pattern
   placeholder = (defined?(prompt) && prompt.presence) || '' %>
<div class="array">
  <%= builder.hidden_field attribute_name %>
  <table>
    <tbody>
    <% (attribute_value.present? ? ActiveSupport::JSON.decode(attribute_value) : []).each_with_index do |e, i| %>
      <%= render 'cms/cis/array_attribute_row',
                 :name        => "#{attribute_name}_#{i}",
                 :value       => e,
                 :pattern     => pattern_x,
                 :placeholder => placeholder %>
    <% end %>
    </tbody>
    <tfoot class="hide">
    <%= render('cms/cis/array_attribute_row',
               :name        => "new_array_attribute_row_#{attribute_name}",
               :value       => '',
               :pattern     => pattern_x,
               :placeholder => placeholder) %>
    </tfoot>
  </table>
  <%= link_to_function(icon('plus', 'add'), "new_array_attribute_row(this)", :class => 'btn btn-mini') %>
</div>
<script type="text/javascript">
  if (!window.new_array_attribute_row) {

    window.new_array_attribute_row = function(source) {
      var table    = $j(source).prev("table"),
          new_html = table.find("tfoot").html(),
          row_id   = "" + new Date().getTime();
      table.find("tbody").append(new_html.replace(new RegExp("new_array_attribute_row", "g"), row_id));
      table.parents("form").attr('data-dirty', 'true');
      var row = table.find("tbody tr:last-child");
      row.find(".entry").focus();
      variableTypeahead(row);
    };

    window.delete_array_attribute_row = function(row) {
      row = $j(row).closest("tr");
      var table = row.parents("table");
      row.remove();
      table.parents("form").attr('data-dirty', 'true');
      update_array_attribute_raw_value(table);
    };

    window.update_array_attribute_raw_value = function(source) {
      var table = $j(source).closest('table');

      var result = table.find("tbody tr").toArray()
          .reduce(function (a, row) {
                    a.push($j(row).find(".entry").val());
                    return a;
                  },
                  []);

      var field = table.prev("input");
      field.val(Object.toJSON(result));
    };
  }
</script>
